package com.yang.controller;

import com.alibaba.fastjson.JSON;
import com.yang.pojo.User;
import com.yang.pojo.User_Info;
import com.yang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userService;

    //用户注册
    @RequestMapping("/register")
    public String addUser(@RequestBody String userJson){
        User user = JSON.parseObject(userJson,User.class);
        int info = userService.addUser(user);
        if(info == 1){
            return "200";
        } else{
            return "500";
        }
    }

    //用户登录
    @RequestMapping("/logging")
    public String queryUserByUN(@RequestBody String userJson){
        User userObject = JSON.parseObject(userJson,User.class);
        User user = userService.inspectLoginUser(userObject.getUsername(),userObject.getPassword());
        if(user != null) {
            if(user.getLoginTime() == null){
                userService.insertUserLoginTime(userObject);
                user.setLoginTime(userObject.getLoginTime());
            }
            return JSON.toJSONString(user);
        } else {
            return "500";
        }
    }

    //退出登录
    @RequestMapping("/outLogin")
    public String exitLogin(@RequestBody String userJson){
        User userObject = JSON.parseObject(userJson,User.class);
        userService.exitLogin(userObject.getUsername());
        return "200";
    }

    //保存用户信息
    @RequestMapping("/saveUserInfo")
    public String saveUserInfo(@RequestBody String userInfoJson){
        int info = 0;
        User_Info userInfo = JSON.parseObject(userInfoJson,User_Info.class);
        User_Info userInfo1 = userService.getUserInfo(userInfo.getUsername());
        if(userInfo1 != null){
            info = userService.updateUserInfo(userInfo);
        } else {
            info = userService.saveUserInfo(userInfo);
        }
        System.out.println(info);
        if(info == 1) {
            return "200";
        } else {
            return "500";
        }
    }

    //获取用户信息
    @RequestMapping("/getUserInfo")
    public String getUserInfo(@RequestBody String userInfoJson){
        User user = JSON.parseObject(userInfoJson,User.class);
        User_Info userInfo = userService.getUserInfo(user.getUsername());
        String user_Info = JSON.toJSONString(userInfo);
        if(user_Info != null) {
            return user_Info;
        } else {
            return "500";
        }
    }

    //上传用户头像
    @RequestMapping("/uploadUserImg")
    public String up(@RequestParam("userImg") MultipartFile picture, HttpServletRequest request) {
        String localUrl = "http://localhost:8081/";
        //获取上传的用户名
        String username = request.getParameter("username");
        //获取文件在服务器的储存位置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        //System.out.println("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            //System.out.println("目录不存在，创建目录:" + filePath);
            filePath.mkdir();
        }
        //获取原始文件名称(包含格式)
        String originalFileName = picture.getOriginalFilename();
        //System.out.println("原始文件名称：" + originalFileName);

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        //System.out.println("文件类型：" + type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        //设置文件新名称: 当前时间+文件名称（不包含格式）
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = date + name + "." + type;
        //System.out.println("新文件名称：" + fileName);

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        try{
            if(!targetFile.exists()){
                targetFile.createNewFile();
                picture.transferTo(targetFile);
            }
            User_Info userInfo = userService.getUserInfo(username);
            userInfo.setUsername(username);
            userInfo.setUserImgName(fileName);
            userInfo.setUserImgPath(path);
            userInfo.setVirPath(localUrl+"upload");
            userService.uploadUserImg(userInfo);
        } catch (IOException e){
            e.printStackTrace();
        }
        return localUrl + "upload/" + fileName;
    }
}
